import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Modal,Image, Popup } from 'antd-mobile';
import Toast from 'antd-mobile/es/components/toast';
import styles from './index.less';
import { Button, Card, message } from 'antd';
import UnorderedListOutlined from '@ant-design/icons/lib/icons/UnorderedListOutlined';
import StarFill from 'antd-mobile-icons/es/StarFill';
import SoundOutlined from '@ant-design/icons/lib/icons/SoundOutlined';
import AudioOutlined from '@ant-design/icons/lib/icons/AudioOutlined';
import { updateScore } from '@/pages/Textbook/service';
import { Uphistory } from '@/pages/Schme/service';
import { CheckCircleOutlined, udp, useAsyncEffect } from '@cscec/udp-mobile-ui/es/util';
import ExclamationCircleOutlined from '@ant-design/icons/lib/icons/ExclamationCircleOutlined';
import { useSpeechService } from '@/util';
import audioPlayer from '../../utils/audioPlayer';
import { useAudioPlay } from '@/hooks/useAudioPlay';
import { recognizeSpeechByFile } from '@/servers/baiduSpeechService';

const ListeningExercise = ({ values, num, length, setNum, wordList }: any) => {
  const [isRecognitionActive, setIsRecognitionActive] = useState<boolean>(false);
  const [userSpeech, setUserSpeech] = useState<string>('');
  //是否第一次选对
  const [isFirstTrue,setIsFirstTrue]=useState(true)
  //控制弹窗
  const [visible, setVisible] = useState(false)
  const [visible1, setVisible1] = useState(false)
  const [transcript,setTranscript] =useState(null)
  const questions = values.tbExerciseOptionVos[0]
  const unitNum = wordList[0]?.unitIdEXName.substring(0, 1)
  const { isPlaying, isLoading, playAudio, stopAudio } = useAudioPlay({});
  const { startRecording, stopRecording, compatibility } = useSpeechService();
  // 当前问题
  const currentQuestion = questions

  const word = values.name
  useEffect(() => {//只在第一次播放
    if (word) {
      //这里会播放单词的音频
      playAudio(word)
    }
  }, [word])

    /**
   * 开始录音处理
   */
  const handleStartRecording = async () => {
    try {
      // 添加兼容性检查
    if (!compatibility.recording) {
      Toast.show('您的浏览器不支持录音功能');
      return;
    }
    
    if (!compatibility.mimeType) {
      Toast.show('无法找到支持的音频格式');
      return;
    }
      await startRecording();
      setIsRecognitionActive(true);
    } catch (error) {
      Toast.show({
        content: `无法开始录音: ${error}`,
        position: 'top'
      });
    }
  };

   /**
   * 停止录音并处理匹配
   */
  const handleStopRecording = async () => {
    try {
      const audioBlob = await stopRecording();
      recognizeSpeechByFile(audioBlob).then((rt:any)=>{
        if(rt.code==200){
          setTranscript(rt.data)
          const url = URL.createObjectURL(audioBlob);
          const audio = new Audio(url);
          audio.play()
          setIsRecognitionActive(false);
        }else{
          message.error('语音识别失败请重试')
        }
      })

    } catch (error) {
      Toast.show({
        content: `录音处理失败: ${error}`,
        position: 'top'
      });
    }
  };

  // 处理点击
  const handleClick = () => {
    if(isRecognitionActive){
      handleStopRecording();
    }else{
      handleStartRecording();
    }
  }
  // 进行语音匹配
  useEffect(()=>{
      if(transcript){
        const str =`您的识别结果为${transcript}`
        message.info(str)
        setUserSpeech(transcript)
      }
  },[transcript])

  const mesArr = ['Great job!', 'Awesome!！', 'Wow, so clever!', 'Perfect!', 'High five!', 'Brilliant!', 'Way to go!', 'You’re amazing!', 'Keep up the good work!']
  const index = Math.floor(Math.random() * (8))
  const errorArr = ['Oops! Try again', 'Not yet.Try again!', 'Almost! Try once more', 'Another try!', 'Not right.Try again!', 'Keep going!']
  const errIndex = Math.floor(Math.random() * (6))
  //翻页功能
  const next = async () => {
    const result = updateScore({
      unitId:values.unitId,
      type:0,
      flag:isFirstTrue?0:1
    })
    if (num + 1 > length) {
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId:values.id,
        completionStatus: 2, studyFlag: 1, historyType: 1
      }).then((rt) => {
        udp.message('当前主题已经学习完毕!')
        udp.close()
      })
    } else {
      //翻页时，设置回true
      setIsFirstTrue(true)
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId:values.id,
        completionStatus: 2,
        studyFlag: 1, historyType: 1
      })
      setNum(num + 1)
    }
  }

  // 处理操作按钮点击
  const handleActionClick = () => {
    if (!userSpeech) return;
const new_str = userSpeech.replace(/[`:_.~!@#$%^&*() \+ =<>?"{}|, \/ ;' \\ [ \] ·~！@#￥%……&*（）—— \+ ={}|《》？：“”【】、；‘’，。、]/g,'');
console.log('新的字符串：', new_str)

    if(new_str==word){
      audioPlayer.playSuccess();//播放音效
      setVisible(true)
    }else{
      audioPlayer.playFailure();//播放音效
      setIsFirstTrue(false)//这里设置不是第一次选对了
      setVisible1(true)
    }
  };
    // 所有单词弹窗
  const [modalvisible, setModalvisible] = useState(false)
  const [current, setCurrent] = useState(1)

  const handleAllWord = () => {
    setModalvisible(true)
  }
  return (
    <>
      <div className={styles["word-header"]}>
        <div className={styles["word"]}>单词{num}/{length}</div>
        <div className={styles["word"]} onClick={handleAllWord}>
          <UnorderedListOutlined />
          所有单词
        </div>

      </div>
      {/* 主要内容 */}
      <div className={styles["main-content"]}>
        <div className={styles["exercise-content"]}>
          {/* 提示文字 */}
          <p className={styles["instruction-text"]}>
            先听单词发音，然后跟读
          </p>

          {/* 单词显示与播放区域 */}
          <div 
          //className="word-audio-container pop-in"
          className={styles["word-audio-container"]}
          >
            <div className={styles["word-card"]}>
              <h2 className={styles["current-word"]}>{currentQuestion.answer}</h2>
            </div>
            
            <Button
              className={isPlaying?styles["play-btn"]:styles["pulse-animation"]}
              onClick={()=>{
                 playAudio(word)
              }}
              disabled={isPlaying}
            >
              <SoundOutlined style={{
                fontSize:"24px"
              }}/>
            </Button>
          </div>

          {/* 跟读交互区域 */}
          <div className={styles["recording-section"]}>
            <Button
              //className={styles[`mic-btn ${isRecognitionActive ? 'recording' : ''}`]}
              className={isRecognitionActive ? styles["mic-btn-recording"]:styles["mic-btn"]}
              onClick={handleClick}
            >
              <AudioOutlined style={{ fontSize:"24px" }} />
            </Button>
            
            {/* <p className={styles["recording-hint"]}>
              点击麦克风开始录音，松手结束录音
            </p> */}
          </div>
        </div>
      </div>

        <div className={styles["actions"]}>
          <Button
            size="large"
            onClick={handleActionClick}
            className={styles["continue-button"]}
            disabled={!userSpeech}
            block
          >
            Check
          </Button>
        </div>
      <Popup
        visible={visible}
        bodyStyle={{
          height: '35vh',
          backgroundColor: '#ffffff',
          borderRadius: '25px 25px 0 0',
          textAlign: 'center',
        }}
      >
        <div
          style={{
            height: '180px',
            color: '#4caf50',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <CheckCircleOutlined
            style={{
              color: '#4caf50',
              fontSize: 'xxx-large',
              display: 'block'
            }} />
          {mesArr[index]}</div>

        <Button
          size="large"
          onClick={() => {
            setVisible(false)
            next()
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            backgroundColor: '#4caf50',
            color: '#ffffff'
          }}
          disabled={!userSpeech}
          block
        >
          Next
        </Button>
      </Popup>
      <Popup
        visible={visible1}
        bodyStyle={{
          height: '35vh',
          background: '#ffffff',
          textAlign: 'center',
          borderRadius: '25px 25px 0 0'
        }}
      >
        <div
          style={{
            height: '180px',
            color: 'red',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <ExclamationCircleOutlined style={{
            color: 'red',
            fontSize: 'xxx-large',
            display: 'block'
          }} />
          {errorArr[errIndex]}</div>
        <Button
          size="large"
          onClick={() => {
            setVisible1(false)
            setUserSpeech('')
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            color: '#ffffff',
            backgroundColor: '#f44336'
          }}
          disabled={!userSpeech}
          block
        >
          Try Again
        </Button>
      </Popup>
       {/* 所有单词弹窗 */}
      <Modal visible={modalvisible}
        bodyClassName={styles["list-modal"]}
        content={
          <div className={styles["list-content"]}>
            <h3 className={styles['list-title']}>{`Unit ${unitNum}：所有单词`}</h3>
            <p className={styles['header-title']}>点击单词直接跳转学习</p>
            <div className={styles["word-list"]}>
              {wordList.map((item, index) => {
                return <div className={current === index + 1 ? styles["word-item-current"] : styles["word-item"]}
                  onClick={() => {
                    setCurrent(index + 1)
                    setNum(index + 1)
                    setModalvisible(false)
                  }}>
                  {item.type==2?<span>{item.name}</span>:<Image
                  height='21px'
                  src={item.imgUrl}
                  fit='contain'
                />}
                  <StarFill className={current === index + 1 ? styles["word-inco-current"] : styles["word-inco"]} />
                </div>
              })}
            </div>
            <Button className={styles["close-button"]}
              onClick={() => {
                setModalvisible(false)
              }}>关闭</Button>
          </div >
        }

        closeOnAction
        closeOnMaskClick={true}
        onClose={() => {
          setModalvisible(false)
        }}
      >

      </Modal >
    </>
  );
};

export default ListeningExercise;